const Router = require('koa-router')
const passport = require('koa-passport')
const formatDate = require('../../utils/dateFormat').formatDate
const router = new Router()
const mongoose = require('mongoose')

const reposIn = require('../../models/RepositoryIn')
const blood = require('../../models/Blood')
const volunteer = require('../../models/Volunteer')
const Repository = require('../../models/Repository')
/**
 * @description test
 */
router.get('/test', async ctx => {
  ctx.body = {
    message: 'success'
  }
})

/**
 * @description 血液入库
 */
router.post('/rk', async ctx => {
  const body = ctx.request.body
  const findResult = await reposIn.find({ blood: body.bloodId })
  if (findResult.length > 0) {
    ctx.status = 400
    ctx.body = { msg: '该血液已经入库' }
  } else {
    const newReposin = new reposIn({
      inDate: body.inDate,
      blood: mongoose.Types.ObjectId(body.bloodId),
      principal: body.principal
    })
    const repositoryDet = await Repository.findById(body.repository)
    // 当前仓储量
    const nowStorage = repositoryDet.nowStorage
    // 修改入仓结果
    const findResult = await blood.findByIdAndUpdate(body.bloodId, { isRepos: 1, reposId: body.repository, reposName: repositoryDet.name })
    await Repository.findByIdAndUpdate(body.repository, { nowStorage: nowStorage + 1 })
    await newReposin
      .save()
      .then(res => {
        ctx.body = []
      })
  }
})

/**
 * @description 入库记录查询
 */
router.get('/page', async ctx => {
  const query = ctx.request.query
  let page = Number(query.page) ? Number(query.page) : 1
  let size = Number(query.per_page) ? Number(query.per_page) : 9999
  let skip = (page - 1) * size
  let ReInNum = query.ReInNum ? new RegExp(query.ReInNum) : /[\s\S]*/
  // console.log('reinnum', ReInNum)
  let findResult = await reposIn.find({ $or: [{ ReInNum: { $regex: ReInNum } }], isDeleted: 0 }).skip(skip).limit(size)
  let totalElement = await reposIn.find({ isDeleted: 0 }).skip(skip).limit(size).countDocuments()
  ctx.status = 200
  ctx.body = {
    current_page: page,
    per_page: size,
    total: totalElement,
    data: findResult
  }
})
/**
 * @description 入库详细（血液信息
 */
router.get('/get', async ctx => {
  const id = ctx.request.query.id
  let findResult = await reposIn.aggregate([
    {
      $lookup: {
        from: 'bloods',
        localField: 'blood',
        foreignField: '_id',
        as: 'blood'
      }
    },
    {
      $match: {
        _id: mongoose.Types.ObjectId(id)
      }
    }
  ])
  if (findResult) {
    // console.log('blood', findResult[0].blood[0])
    const vId = findResult[0].blood[0].volunteerId
    // console.log('vId', vId)
    let findVolunteer = await volunteer.findById(vId)
    // console.log('findV', findVolunteer)
    if (findVolunteer) {
      ctx.body = {
        _id: findResult[0]._id,
        ReInNum: findResult[0].ReInNum,
        inDate: findResult[0].inDate,
        blood: findResult[0].blood[0],
        volunteer: findVolunteer
      }
    }
  } else {
    ctx.status = 400
    ctx.body = []
  }
})
/**
 * @description 删除入库记录
 */
router.get('/delete', async ctx => {
  const id = ctx.request.body.id
  try {
    const updateResult = await reposIn.findByIdAndUpdate(id, { isDeleted: 1 })
    if (updateResult) {
      ctx.status = 200
      ctx.body = []
    } else {
      ctx.status = 400
      ctx.response.status = 400
      ctx.response.message = '数据库中无该条数据'
      ctx.body = {
        msg: '删除失败'
      }
    }
  } catch { }
})
module.exports = router.routes()